﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZBJF.Warranty.DAL
{
    public static class DatabaseExtend
    {
        public static DataTable SqlQueryForDataTatable(this Database db, string sql, SqlParameter[] parameters)
        {
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection())
            {
                conn.ConnectionString = db.Connection.ConnectionString;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = sql;
                    if (parameters.Length > 0)
                    {
                        foreach (var item in parameters)
                        {
                            cmd.Parameters.Add(item);
                        }
                    }
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataTable table = new DataTable();
                    adapter.Fill(table);
                    return table;
                }
            }
        }

        public static object ExecuteScalar(this Database db, string sql, SqlParameter[] parameters)
        {
            using (SqlConnection conn = new System.Data.SqlClient.SqlConnection())
            {
                conn.ConnectionString = db.Connection.ConnectionString;
                if (conn.State != ConnectionState.Open)
                {
                    conn.Open();
                }
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = sql;
                    if (parameters.Length > 0)
                    {
                        foreach (var item in parameters)
                        {
                            cmd.Parameters.Add(item);
                        }
                    }
                    return cmd.ExecuteScalar();
                }
            }
        }
    }
}
